package com.study.d012Components.listview;

import javafx.application.Application;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.ListView.EditEvent;
import javafx.scene.control.cell.CheckBoxListCell;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;

/**
 * 通过复选框的方式使用 ListView
 *
 * @description
 * @author xtayhame date 2020年3月13日 version since v1.0
 */
public class ListViewWithCheckBoxListCell extends Application {
	public static void main(String[] args) {
		launch(args);
	}

	@Override
	public void start(Stage stage) throws Exception {
		AnchorPane anchorPane = new AnchorPane();
		ObservableList<Student> datas = FXCollections.observableArrayList();
		datas.add(new Student("张三", 14));
		datas.add(new Student("李四", 15));
		datas.add(new Student("王五", 16));

		ListView<Student> listView = new ListView<Student>(datas);
		listView.setPrefSize(200, 150);

		// 第三种：通过复选框的方式
		Callback<ListView<Student>, ListCell<Student>> callback3 = CheckBoxListCell
				.forListView(new Callback<Student, ObservableValue<Boolean>>() {
					@Override
					public ObservableValue<Boolean> call(Student param) {
						if (param.getName().equals("张三")) {
							param.setIsCheck(true);
							return param.getIsCheckProperty();
						}
						param.setIsCheck(false);
						return param.getIsCheckProperty();
					}
				}, new StringConverter<Student>() {

					@Override
					public String toString(Student object) {
						// TODO Auto-generated method stub
						return object.getName();
					}

					@Override
					public Student fromString(String string) {
						// TODO Auto-generated method stub
						return null;
					}
				});

		//listView.setEditable(true);
		listView.setCellFactory(callback3);

		anchorPane.getChildren().add(listView);
		AnchorPane.setTopAnchor(listView, 10.0);
		AnchorPane.setLeftAnchor(listView, 20.0);
		stage.setScene(new Scene(anchorPane, 400, 500));
		stage.show();


		//点击时 ，判断是否选中
		listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Student>() {
			@Override
			public void changed(ObservableValue<? extends Student> observable, Student oldValue, Student newValue) {
				System.out.println("当前用户：" + newValue.getName() + "     是否选中：" + newValue.isCheck());
			}
		});



	}
}
